from rest_framework.decorators import action
from rest_framework.generics import RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from hongt1026.serializers import SpitDetailSerializers, CommentSerializerForCreate, ArticleSerializerForDetail, \
    ArticleSerializerForCreate
from six_it.models import Article, Spit


class ArticleDetailView(ModelViewSet):

    queryset = Article.objects.all()

    def retrieve(self, request, *args, **kwargs):
        article = super().get_object()
        article.visits += 1
        article.save()
        s = ArticleSerializerForDetail(instance=article)
        return Response(s.data)


class PublishArticleView(ModelViewSet):
    queryset = Article.objects.all()

    def create(self, request, *args, **kwargs):

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            request_params = request.data
            request_params['user'] = user.id
            serializer = ArticleSerializerForCreate(data=request_params)
            serializer.request = request
            serializer.is_valid(raise_exception=True)
            article = serializer.save()
            return Response({'success': True, 'message': '发表成功', 'articleid': article.id})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


class PublishCommentView(ModelViewSet):
    queryset = Article.objects.all()

    @action(methods=['post'], detail=True)
    def publish_comment(self, request, pk):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            article = self.get_object()
            article.comment_count += 1
            article.save()
            request_params = request.data
            request_params['user'] = user.id
            request_params['article'] = article.id

            s = CommentSerializerForCreate(data=request_params)
            s.is_valid(raise_exception=True)
            s.save()
            return Response({'success': True, 'message': '评论成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


class SpitDetailView(RetrieveAPIView):
    serializer_class = SpitDetailSerializers
    queryset = Spit.objects.all()


class SpitChildrenView(APIView):

    def get(self, request, pk):
        queryset = Spit.objects.filter(parent_id__exact=pk)
        serializer = SpitDetailSerializers(queryset, many=True)

        return Response(serializer.data)
